# -*- coding: utf-8 -*-
import sys

sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
from urllib.parse import urlencode
from common.helper import Helper
import asyncio, aiohttp
import json


class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "金刚保长期意外伤害保险产品计划"

    # 生成产品数据
    def genProductInfo(self):
        plan = {
            "planF": {
                # 年龄段
                "year": [str(i) for i in range(18, 41)],
                # 性别
                "gender": ["M", "F"],
                # 保障期限
                "days": ["10y"],
                # 保额
                "money": ["100000", "200000", "300000", "500000", "1000000", "1500000"],
                # 交费间隔
                "interval": ["5"],
                # 交费类型
                "payType": ["年交"],
                # 猝死保额
                "sudden_death": ["0", "1"]
            },
            "planG": {
                # 年龄段
                "year": [str(i) for i in range(18, 41)],
                # 性别
                "gender": ["M", "F"],
                # 保障期限
                "days": ["20y"],
                # 保额
                "money": ["100000", "200000", "300000", "500000", "1000000", "1500000"],
                # 交费间隔
                "interval": ["5", "10"],
                # 交费类型
                "payType": ["年交"],
                # 猝死保额
                "sudden_death": ["0", "1"]
            },
            "planH": {
                # 年龄段
                "year": [str(i) for i in range(18, 41)],
                # 性别
                "gender": ["M", "F"],
                # 保障期限
                "days": ["30y", "70s", "80s"],
                # 保额
                "money": ["100000", "200000", "300000", "500000", "1000000", "1500000"],
                # 交费间隔
                "interval": ["5", "10", "20"],
                # 交费类型
                "payType": ["年交"],
                # 猝死保额
                "sudden_death": ["0", "1"]
            },
            "planJ": {
                # 年龄段
                "year": [str(i) for i in range(18, 41)],
                # 性别
                "gender": ["M", "F"],
                # 保障期限
                "days": ["zs"],
                # 保额
                "money": ["100000", "200000", "300000", "500000", "1000000", "1500000"],
                # 交费间隔
                "interval": ["5", "10", "20", "30"],
                # 交费类型
                "payType": ["年交"],
                # 猝死保额
                "sudden_death": ["0", "1"]
            },
            "planK": {
                # 年龄段
                "year": [str(i) for i in range(41, 46)],
                # 性别
                "gender": ["M", "F"],
                # 保障期限
                "days": ["10y"],
                # 保额
                "money": ["100000", "200000", "300000", "500000", "1000000"],
                # 交费间隔
                "interval": ["5"],
                # 交费类型
                "payType": ["年交"],
                # 猝死保额
                "sudden_death": ["0", "1"]

            },
            "planL": {
                # 年龄段
                "year": [str(i) for i in range(41, 46)],
                # 性别
                "gender": ["M", "F"],
                # 保障期限
                "days": ["20y"],
                # 保额
                "money": ["100000", "200000", "300000", "500000", "1000000"],
                # 交费间隔
                "interval": ["5", "10"],
                # 交费类型
                "payType": ["年交"],
                # 猝死保额
                "sudden_death": ["0", "1"]

            },
            "planQ": {
                # 年龄段
                "year": [str(i) for i in range(41, 46)],
                # 性别
                "gender": ["M", "F"],
                # 保障期限
                "days": ["30y", "70s", "80s", "zs"],
                # 保额
                "money": ["100000", "200000", "300000", "500000", "1000000"],
                # 交费间隔
                "interval": ["5", "10", "20"],
                # 交费类型
                "payType": ["年交"],
                # 猝死保额
                "sudden_death": ["0", "1"]

            },
            "planW": {
                # 年龄段
                "year": [str(i) for i in range(46, 46)],
                # 性别
                "gender": ["M", "F"],
                # 保障期限
                "days": ["10y"],
                # 保额
                "money": ["100000", "200000", "300000", "500000", "1000000"],
                # 交费间隔
                "interval": ["5"],
                # 交费类型
                "payType": ["年交"],
                # 猝死保额
                "sudden_death": ["0", "1"]

            },
            "planE": {
                # 年龄段
                "year": [str(i) for i in range(46, 51)],
                # 性别
                "gender": ["M", "F"],
                # 保障期限
                "days": ["20y", "30y", "70s", "80s", "zs"],
                # 保额
                "money": ["100000", "200000", "300000", "500000", "1000000"],
                # 交费间隔
                "interval": ["5", "10"],
                # 交费类型
                "payType": ["年交"],
                # 猝死保额
                "sudden_death": ["0", "1"]

            },
            "planR": {
                # 年龄段
                "year": [str(i) for i in range(51, 56)],
                # 性别
                "gender": ["M", "F"],
                # 保障期限
                "days": ["10y"],
                # 保额
                "money": ["100000", "200000", "300000", "500000"],
                # 交费间隔
                "interval": ["5"],
                # 交费类型
                "payType": ["年交"],
                # 猝死保额
                "sudden_death": ["0", "1"]

            },
            "planT": {
                # 年龄段
                "year": [str(i) for i in range(51, 56)],
                # 性别
                "gender": ["M", "F"],
                # 保障期限
                "days": ["20y", "30y", "70s", "80s", "zs"],
                # 保额
                "money": ["100000", "200000", "300000", "500000"],
                # 交费间隔
                "interval": ["5", "10"],
                # 交费类型
                "payType": ["年交"],
                # 猝死保额
                "sudden_death": ["0", "1"]

            }

        }

        for k in plan:
            for v in product(plan[k]["year"], plan[k]["gender"], plan[k]["days"], plan[k]["money"], plan[k]["interval"],
                             plan[k]["payType"], plan[k]["sudden_death"]):
                data = Helper.formatProductInfo(plan[k], v)
                data["sudden_death"] = data["money"] if data["sudden_death"] != "0" else "0"
                self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(**data))
                self.mysql._conn.commit()
                print(domain[self.name]["insert_sql"].format(**data))

    # 异步请求
    async def requestJson(self, data):
        birth = str(2020 - int(data["year"]))
        sex = "0" if data["gender"] == "M" else "1"
        if "y" in data["days"]:
            period = data["days"].replace("y", "年")
        elif "z" in data["days"]:
            period = "终身"
        else:
            period = data["days"].replace("s", "岁")
        init_items = ['{"dutyCode":"126001","dutyAmnt":"' + data["money"] + '"}']
        if data["sudden_death"] == "0":
            pass
        else:
            init_items.append('{"dutyCode":"126002","dutyAmnt":' + data["sudden_death"] + '}')
        duties = ','.join(init_items)
        params = {
            "insuredsStr": '[{"birthday":"' + birth + '-01-01","sex":"' + sex + '","planInfos":[{"riskCode":"A180","mainRiskCode":"A180","planCode":"29","planPeriod":"' + period + '","payType":"12","payEndYearFlag":"Y","payEndYear":5,"dutys":[' + duties + ']}]}]',
            "isOrder": "0",
            "productID": "32"
        }

        payload = urlencode(params).replace("+", "")
        async with aiohttp.ClientSession() as session:
            async with session.post(url=domain[self.name]["url"], headers=domain[self.name]["header"],
                                    data=payload) as resp:
                res = await resp.text()

                price = json.loads(res)["data"]["data"]["insureds"][0]["insurerPrem"]
                if price:
                    rec = {
                        "name": self.name,
                        "id": data["id"],
                        "price": Helper.decimalParse(price)

                    }
                    print(rec)
                    self.mysql.updatePrice(rec)
                else:
                    rec = {
                        "name": self.name,
                        "id": data["id"],
                        "state": 3

                    }
                    self.mysql.updateTask(rec)
                    print("\n/*产品价格更新失败:%d*/" % data["id"])

    # limit 100
    def getLimitData(self):

        Sql = 'SELECT	* FROM `' + self.name + '` WHERE `state` = 0 LIMIT 100'

        self.mysql.cursor.execute(Sql)

        for row in self.mysql.cursor.fetchall():
            data = {
                "name": self.name,
                "id": row["id"],
                "state": 1
            }
            self.mysql.updateTask(data)
            yield row

    # 执行任务
    def asyncTask(self):

        while True:

            try:

                tasks = [self.requestJson(data) for data in self.getLimitData()]

                event_loop = asyncio.get_event_loop()

                event_loop.run_until_complete(asyncio.gather(*tasks))

            except:

                break
